import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/model/device_list_entity.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/delivery_user.dart';
import 'package:wch/page/set_wifi.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../helper/event_manager.dart';
import '../model/ble.dart';
import '../native/native.dart';
import '../utils/loading_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/alert_view.dart';

class WifiSetPage extends StatefulWidget {
  const WifiSetPage({super.key});

  @override
  State<WifiSetPage> createState() => _WifiSetPageState();
}

class _WifiSetPageState extends State<WifiSetPage> with EventManagerInterface, TickerProviderStateMixin{

  List<DeviceListData> deviceList = [];
  List<BleModel> dataList = [
  ];
  Timer? connTimer;

  BleModel? curModel;

  OverlayEntry? entry;

  String? selectedUserId;
  ///是否搜索中
  bool isSearching = false;
  Timer? searchTimer;

  AnimationController? animationController;
  Animation<double>? animation;

  @override
  void initState() {
    EventManager.getIns().addObserver(this);

    isSearching = true;

    /// 动画持续时间是 3秒，此处的this指 TickerProviderStateMixin
    animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )
      ..repeat();
    animation = Tween<double>(begin: 1, end: 0).animate(animationController!);

    NetBusiness().deviceList().then((onValue){
      deviceList = onValue.data!;
      NativeUtils.scanAIO();
      searchTimer = Timer(Duration(seconds: 10), (){
        setState(() {
          isSearching = false;
        });
      });
      NativeUtils.bleCentralState();
    });
  }

  @override
  void dispose() {
    animationController?.dispose();
    super.dispose();
    ///释放
    NativeUtils.stopScanAIO();
    NativeUtils.disconnectAIO();
    EventManager.getIns().removeObserver(this);

    searchTimer?.cancel();
    connTimer?.cancel();
  }

  //旋转
  Widget buildRotationTransition() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RotationTransition(
            //设置动画的旋转中心
            alignment: Alignment.center,
            //动画控制器
            turns: animation!,
            //将要执行动画的子view
            child: Image.asset(searchLoadingIcon, width: 40.w, height: 40.w,),
          ),
          VerPadding(14.h),
          F14TitleText('搜索中...', color: Color(0xFF515151)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      title: 'Wi-Fi设置',
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 15.h),
        child: Center(
          child: isSearching ? buildRotationTransition() : dataList.isEmpty ? Column(
            children: [
              VerPadding(98.h),
              Image.asset(aioEmptyIcon, width: 71.w, height: 52.h,),
              VerPadding(4.h),
              F12TitleText('未搜索到任何设备', color: Color(0xFF868686)),
            ],
          ) : ListView.separated(itemBuilder: (ctx,id){
            if (id == 0) {
              return Container(
                padding: EdgeInsets.only(left: 15.w),
                height: 30.h,
                child: F15TitleText(
                  '选择相关设备',
                  color: Color(0xFF424242),
                ),
              );
            }
            return _getItem(id-1);
          }, separatorBuilder: (ctx, id){
            return Divider(height: 10.h, thickness: 10.h, color: Colors.transparent,);
          }, itemCount: dataList.length+1),
        ),
      ),
      rightBtn: GestureDetector(
        onTap: (){
          NativeUtils.bleCentralState();
          NativeUtils.disconnectAIO();
          NativeUtils.stopScanAIO();
          setState(() {
            dataList.clear();
          });
          NativeUtils.scanAIO();
          isSearching = true;
          connTimer?.cancel();
          searchTimer?.cancel();
          searchTimer = Timer(Duration(seconds: 10), (){
            setState(() {
              isSearching = false;
            });
          });
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
          child: F14TitleText('刷新', color: themeColor,),
        ),
      ),
    );
  }

  Widget _getItem(int id) {
    BleModel model = dataList[id];
    return InkWell(
      onTap: (){
        curModel = model;
        if (!model.isConnected) {
          ToastUtils.showToast(msg: '正在连接中断蓝牙');
          NativeUtils.connectAIO(arguments: {'deviceName': model.deviceName, 'mac': model.mac});
          connTimer?.cancel();
          connTimer = Timer(Duration(seconds: 20), (){
            ToastUtils.showToast(msg: '连接终端蓝牙失败，请重试');
          });
        } else {
          if (model.userModel?.name == null) {
            NavigatorUtil.push(context, DeliveryUserPage(bleModel: dataList[id],));
          } else {
            NavigatorUtil.push(context, StartSetWifiPage(bleModel: dataList[id]));
          }
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 25.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
        ),
        child: Row(
          children: [
            Image.asset(aioIcon, width: 41.w, height: 41.w,),
            HorPadding(7.5.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children:  model.userModel?.sex == null ? [F14TitleText('设备号：${model.deviceName}', color: Color(0xFF3E3F42)),] : [
                  F14TitleText('设备号：${model.deviceName}', color: Color(0xFF3E3F42)),
                  Container(
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        VerPadding(7.5.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            F12TitleText(_getUserName(id), color: F2TextColor),
                            HorPadding(5.w),
                            Image.asset(model.userModel?.sex == '男' ? patientMaleIcon : patientFemaleIcon, width: 10.w, height: 10.w,),
                            HorPadding(14.w),
                            F12TitleText(_getUserMobile(id), color: F2TextColor),
                          ]
                        ),
                      ]
                    ),
                  )
                ],
              ),
            ),
            Image.asset(arrowRightPng, width: 11.w, height: 11.w,),
          ],
        ),
      ),
    );
  }

  String _getUserName(int id) {
    BleModel model = dataList[id];
    if (model.userModel == null)  return '';
    if (model.userModel!.name == null)  return '';
    if (model.userModel!.name!.length > 4) {
      return '${model.userModel!.name!.substring(0, 3)}...';
    }
    return model.userModel!.name!;
  }
  String _getUserMobile(int id) {
    BleModel model = dataList[id];
    if (model.userModel == null)  return '';
    if (model.userModel!.mobile == null)  return '';
    return model.userModel!.mobile!;
  }

  void showDeviceLogic(Map<dynamic, dynamic> data) {
    String channel = data['channelName'];
    int code = data['code'];
    String deviceName = data['deviceName'];
    bool isConnected = data['isConnected'];
    String? mac = data['mac'];
    LogUtils.log('deviceName=$deviceName');

    BleModel model = BleModel(channelName: channel, code: code, deviceName: deviceName, isConnected: isConnected, mac: mac);
    model.userModel = UserModel(name: null, sex: null, mobile: '');
    for(int i = 0; i < deviceList.length; i ++) {
      if (deviceList[i].deviceBluetoothNumber == deviceName) {
        model.deviceId = deviceList[i].id;
        LogUtils.log('model.deviceId=${model.deviceId}');
        model.userModel = UserModel(name: deviceList[i].sickPersonName, sex: deviceList[i].sickPersonSex, mobile: deviceList[i].mobile);
        LogUtils.log('mobile=${model.userModel!.mobile}');
        break;
      }
    }

    setState(() {
      dataList.add(model);
      isSearching = false;
      searchTimer?.cancel();
    });

  }

  @override
  void notify(String methodName, Map<dynamic, dynamic> data) {
    // TODO: implement notify
    if (methodName == eventScanAIO) {
      showDeviceLogic(data);
    } else if (methodName == eventBleCentralState) {
      int isOpen = data['BLECentralStatus'];
      if (isOpen == 0) {
        entry = OverlayEntry(builder: (ctx){
          return CommonAlert(title: '温馨提示', msg: '请检查手机蓝牙是否打开', callback: (id){}, leftBtnText: '确定', isSingleBtn: true, entry: entry!);
        });
        Overlay.of(context).insert(entry!);
        NativeUtils.stopScanAIO();
      } else if (isOpen == -1) {
        entry = OverlayEntry(builder: (ctx){
          return CommonAlert(title: '温馨提示', msg: '请检查蓝牙权限是否打开', callback: (id){}, leftBtnText: '确定', isSingleBtn: true, entry: entry!);
        });
        Overlay.of(context).insert(entry!);
        NativeUtils.stopScanAIO();
      }
    } else if (methodName == eventConnectStatus) {
      String deviceName = data['deviceName'];
      bool isConnected = data['isConnected'];

      if (isConnected) {
        Loading.getIns().hide();
        connTimer!.cancel();
        if (curModel!.userModel?.name == null) {
          NavigatorUtil.push(context, DeliveryUserPage(bleModel: curModel!,));
        } else {
          NavigatorUtil.push(context, StartSetWifiPage(bleModel: curModel!));
        }
      }

      for (int i = 0; i < dataList.length; i ++) {
        BleModel entity = dataList[i];
        if (entity.deviceName == deviceName) {
          entity.isConnected = isConnected;
          break;
        }
      }
    }
  }

}
